package com.andatsoft.laisim.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewManager;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.ViewSwitcher.ViewFactory;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.adapter.MainPagerAdapter;
import com.andatsoft.laisim.asynctask.AlbumArtGettingTask;
import com.andatsoft.laisim.audioeffect.AudioEffectManager;
import com.andatsoft.laisim.config.LaisimConfig;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.dialog.MessageBox;
import com.andatsoft.laisim.entity.Playlist;
import com.andatsoft.laisim.entity.Song;
import com.andatsoft.laisim.service.PlayerService;
import com.andatsoft.laisim.service.PlayerService.RepeatMode;
import com.andatsoft.laisim.theme.Skin;
import com.andatsoft.laisim.theme.Theme;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.Animator;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.utils.ToastMessage;
import com.andatsoft.laisim.utils.Utils;
import com.andatsoft.laisim.view.LaisimBaseAnimation;
import com.andatsoft.laisim.view.MainAlbumArtFragment;
import com.andatsoft.laisim.view.MainLyricsFragment;
import com.andatsoft.laisim.view.MainSongListFragment;
import com.andatsoft.laisim.view.SlimProgressBar;
import com.andatsoft.laisim.view.SlimProgressBar.SlimProgressClicked;
import com.andatsoft.laisim.view.Toolbox;

@SuppressLint("NewApi")
public class MainActivity extends BaseFragmentActivity implements
		OnGestureListener {
	public static final String INTENT_DATA_MAIN_EDIT_TAGS_SONG_ID = "main.edittags.songid";
	public static final String INTENT_DATA_MAIN_VIEW_DETAILS_SONG_ID = "main.details.songid";

	// Views
	private ViewPager mMainPager;
	private ImageView mImgViewFavorite;
	// private ArcProgressBar mArcProgressBarAndPlay;
	// private SeekBar mSeekBarPlaying;
	private SlimProgressBar mSlimProgress;
	private Button mBtnPlay;
	private Button mBtnNext;
	private Button mBtnPrevious;
	private Button mBtnRepeat;
	private Button mBtnShuffle;
	private Button mBtnEq;
	private Button mBtnBassboost;
	private TextView mTvSongTitle;
	private TextView mTvArtist;
	private TextSwitcher mTextSwitcherCurrentIndex;
	private TextView mTvCurrentDuration;
	private TextView mTvDuration;
	private TextView mTvTotalSong;
	private TextView mTvSongExtras;
	private TextView mTvShortcut;
	private MessageBox mMessageBox;
	private GestureDetectorCompat mGesture;

	private LinearLayout mLinearlayoutMainBg;
	private LinearLayout mLayoutMainHeaderContent;
	private LaisimBaseAnimation mLaisimMainAnimation;

	private Toolbox mToolbox;
	private LinearLayout mLayoutTips;
	// private ImageSwitcher mPagerMainImgSwitcherAlbumArt;

	private List<Fragment> mFragmentList;
	private Playlist mPlaylist;
	// private ArrayList<String> mSongAddressList;
	private int mCurrentSongIndex = -1;// For text animation
	private Bitmap mAlbumArtBitmap;
	private DataBaseAccess mDatabase;
	private boolean mShouldChangeBg;
	private boolean mShouldUpdateLyrics;
	private boolean mIsMessageBoxShowing;
	private boolean mIsMainPagerLyrics;

	private ToastMessage mToast;

	// private MainSongListFragment mMainSongListFragment;
	// private MainAlbumArtFragment mMainAlbumArtFragment;
	// private MainLyricsFragment mMainLyricsFragment;

	// Player service
	private PlayerService mPlayerService;
	private boolean mIsBoundService;
	private boolean mNeedToUpdateUI = true;
	private boolean mIsDisplayAlbumArt;
	private boolean mIsNeedChangedAlbumArt;
	private boolean mIsNeedToBlur;

	// Theme
	private Theme mTheme;
	private Skin mSkin;

	private ServiceConnection mPlayerServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mPlayerService = null;
		}

		// called when bind service called.
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mPlayerService = ((PlayerService.LocalBinder) service).getService();
			// get song from service
			if (mPlaylist.getCount() <= 0)
				mPlaylist.setSongList(mPlayerService.getSongList());
			if (mNeedToUpdateUI) {
				// updateUI();
				mPlayerService.sendBroadCastSongInfoData();
				mPlayerService.notifySkinReleased(false);
				mShouldDisplayNotification = mPlayerService.isPlaying();
				if (mPlayerService.isPlaying())
					mPlayerService.displayNotification(mPlayerService
							.isPlaying());
				mPlayerService.updateWidget(mPlayerService.isPlaying());
			}
			// update song list adapter
			if (mFragmentList.size() > 0)
				((MainSongListFragment) mFragmentList.get(0)).updateAdapter();
		}
	};

	public void doBindService() {
		bindService(new Intent(MainActivity.this, PlayerService.class),
				mPlayerServiceConnection, Context.BIND_AUTO_CREATE);
		// Log.d("Bind", "bind" + bo);
		mIsBoundService = true;
	}

	public void doUnBindService() {
		unbindService(mPlayerServiceConnection);
		mIsBoundService = false;
	}

	public PlayerService getPlayerService() {
		return mPlayerService;
	}

	private BroadcastReceiver mBroadcastUpdateSongInfo = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mPlayerService == null) {
				return;
			}
			Log.i("mainac",
					"mBroadcastUpdateSongInfo"
							+ mPlayerService.getCurrentSongIndex());
			if (mPlayerService.getCurrentSong() == null) {
				resetLaiSimUI();
			} else {
				// new song played, new lyrics should be loaded.
				mShouldUpdateLyrics = true;
				if (mCurrentSongIndex == mPlayerService.getCurrentSongIndex())
					mIsNeedToBlur = true;
				updateUI();
				// download albumart if not exist
				if (getCurrentSongId() != -1) {
					// check if song has album art
					if (!mPlayerService.getCurrentSong().hasAlbumArt()) {
						// check if song has downloaded album art
						if (mFragmentList.size() > 1) {
							boolean re = ((MainAlbumArtFragment) mFragmentList
									.get(1))
									.isSongHadAlbumArt(getCurrentSongId());
							if (re) {
								new AlbumArtGettingTask(getApplicationContext())
										.execute(getCurrentSongId());
							}
						}
					}

				}
			}
		}
	};

	private BroadcastReceiver mBroadcastPauseStopSong = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mPlayerService == null)
				return;
			updatePlayingStatus();
		}
	};

	private BroadcastReceiver mBroadcastUpdatePlayedTime = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mPlayerService == null)
				return;
			int curDur = intent.getIntExtra(
					Common.BROADCAST_SONG_CURRENT_DURATION, 0);
			// mSeekBarPlaying.setProgress(curDur);
			mSlimProgress.setProgress(curDur);
			// int progress = (curDur * 100) / dur;
			String curDurStr = Utils.convertTimeToString(curDur);
			mTvCurrentDuration.setText(curDurStr);
			int dur = mPlayerService.getCurrentSongDuration();
			if (curDur + 1000 >= dur) // almost finish playing
			{
				if (!mShouldChangeBg) {
					changeMainLayoutEffect();
				}
			}
		}
	};

	private int getLaunchTime() {
		SharedPreferences sp = getSharedPreferences(Common.SP_MAIN_NAME,
				MODE_PRIVATE);
		return sp.getInt(Common.SP_MAIN_LAUNCH_TIME, 0);
	}

	private void showTips() {
		mLayoutTips = (LinearLayout) findViewById(R.id.layout_tips);
		getLayoutInflater().inflate(R.layout.tips_main, mLayoutTips, true);
		mLayoutTips.setVisibility(View.VISIBLE);
		// if (Utils.androidOs > Common.ANDROID_OS_GINGERBREAD) {
		Animator.applyAlphaAnimation(mLayoutTips, 350, null, 0.0f, 0.8f);
		// }

		Button btnClose = (Button) findViewById(R.id.btn_tips_close);
		btnClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				closeTips();
			}
		});
	}

	private com.nineoldandroids.animation.Animator.AnimatorListener mAnimatorTip = new com.nineoldandroids.animation.Animator.AnimatorListener() {

		@Override
		public void onAnimationStart(com.nineoldandroids.animation.Animator arg0) {

		}

		@Override
		public void onAnimationRepeat(
				com.nineoldandroids.animation.Animator arg0) {

		}

		@Override
		public void onAnimationEnd(com.nineoldandroids.animation.Animator arg0) {
			unbindDrawables(mLayoutTips);
			mLayoutTips.setVisibility(View.GONE);
		}

		@Override
		public void onAnimationCancel(
				com.nineoldandroids.animation.Animator arg0) {

		}
	};

	private void closeTips() {
		Animator.applyAlphaAnimation(mLayoutTips, 500, mAnimatorTip, 0.8f, 0.0f);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (getSelectedSkin() == null
				|| getSelectedSkin().getBassBtnOff() == null
				|| ((BitmapDrawable) getSelectedSkin().getBassBtnOff())
						.getBitmap().isRecycled()) {
			MainActivity.this.finish();
			Toast.makeText(getApplicationContext(),
					getString(R.string.toast_laisim_error), Toast.LENGTH_LONG)
					.show();
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// Get theme
		mTheme = ThemeManager.getSelectedTheme();

		mSkin = ThemeManager.getSelectedSkin();
		if (mTheme == null) {
			ThemeManager.loadTheme(getApplicationContext());
			mTheme = ThemeManager.getSelectedTheme();
		}
		if (getLaunchTime() <= 1) {
			showTips();
		}
		initViews();
		setupListeners();
		initVars();
		mIsDisplayAlbumArt = isAlbumArt();
		initPager();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			// showToolbox();
			showToolbox();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBackPressed();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (!mIsBoundService)
			doBindService();
		mNeedToUpdateUI = true;
	}

	// //////////////////////////////////////////////////////
	//
	// Initialize resources...
	//
	// //////////////////////////////////////////////////////

	private void initViews() {
		// View pager
		mMainPager = (ViewPager) findViewById(R.id.pager_main);

		mLinearlayoutMainBg = (LinearLayout) findViewById(R.id.layout_bg);
		mLayoutMainHeaderContent = (LinearLayout) findViewById(R.id.layout_main_header_content);
		mLaisimMainAnimation = (LaisimBaseAnimation) findViewById(R.id.laisim_main_animation);
		mToolbox = (Toolbox) findViewById(R.id.layout_tool_box);

		mSlimProgress = (SlimProgressBar) findViewById(R.id.progress_and_play);
		mBtnPlay = (Button) findViewById(R.id.btn_main_play);
		mBtnNext = (Button) findViewById(R.id.btn_main_next);
		mBtnPrevious = (Button) findViewById(R.id.btn_main_previous);
		mBtnShuffle = (Button) findViewById(R.id.btn_main_shuffle);
		mBtnRepeat = (Button) findViewById(R.id.btn_main_repeat);
		mBtnEq = (Button) findViewById(R.id.btn_main_eq);
		mBtnBassboost = (Button) findViewById(R.id.btn_main_bassbooster);
		mImgViewFavorite = (ImageView) findViewById(R.id.img_main_favorite);

		mTvCurrentDuration = (TextView) findViewById(R.id.tv_main_played_time);
		mTvDuration = (TextView) findViewById(R.id.tv_main_total_time);
		mTvTotalSong = (TextView) findViewById(R.id.tv_main_total_song);
		mTvSongExtras = (TextView) findViewById(R.id.tv_main_extra_info);
		mTvSongExtras.setSelected(true);
		mTvShortcut = (TextView) findViewById(R.id.tv_main_shortcut_toolbox);
		mTvArtist = (TextView) findViewById(R.id.tv_main_artist);
		mTvSongTitle = (TextView) findViewById(R.id.tv_main_song_title);
		mTextSwitcherCurrentIndex = (TextSwitcher) findViewById(R.id.textswitcher_main_current_song_index);

		mTextSwitcherCurrentIndex.setFactory(new ViewFactory() {

			@Override
			public View makeView() {
				return setupTextForSwitcher(mTheme.getHSTitleColor(), 12);
			}
		});

		setupAnimationForTextSwitcher(mTextSwitcherCurrentIndex,
				R.anim.fade_in_fast, R.anim.fade_out_fast);
	}

	private void applyTheme() {
		if (mTheme == null)
			mTheme = ThemeManager.getSelectedTheme();
		// edge and glow effect
		setEdgeEffectColor(mTheme.getEdgeColorEffect());
		setGlowEffectColor(mTheme.getGrowColorEffect());
		// header
		setAlpha((LinearLayout) findViewById(R.id.layout_main_header_bg),
				mTheme.getHSBackgroundAlpha());
		((LinearLayout) findViewById(R.id.layout_main_header_bg))
				.setBackgroundColor(mTheme.getMainBackgroundColor());

		mTvSongTitle.setTextColor(mTheme.getHSTitleColor());
		mTvSongTitle.setTextColor(mTheme.getHSTitleColor());

		mTvArtist.setTextColor(mTheme.getHSArtistColor());
		mTvArtist.setTextColor(mTheme.getHSArtistColor());

		TextView tv = (TextView) mTextSwitcherCurrentIndex.getChildAt(0);
		tv.setTextColor(mTheme.getNormalTextColor());
		tv = (TextView) mTextSwitcherCurrentIndex.getChildAt(1);
		tv.setTextColor(mTheme.getNormalTextColor());

		// Body (album art)
		// No need to update because the body is managed by the fragment.

		// Footer
		setAlpha((LinearLayout) findViewById(R.id.layout_main_footer_bg),
				mTheme.getFSBackgroundAlpha());
		((LinearLayout) findViewById(R.id.layout_main_footer_bg))
				.setBackgroundColor(mTheme.getMainBackgroundColor());

		mTvCurrentDuration.setTextColor(mTheme.getNormalTextColor());
		mTvDuration.setTextColor(mTheme.getNormalTextColor());
		mTvTotalSong.setTextColor(mTheme.getNormalTextColor());
		mTvSongExtras.setTextColor(mTheme.getNormalTextColor());
		mTvShortcut.setTextColor(mTheme.getNormalTextColor());

		mLaisimMainAnimation.applyTheme();

	}

	private void applySkin() {
		Log.e("applyskin", "apply skin called");
		if (mSkin == null)
			return;
		setDrawableForView(mBtnNext, mSkin.getNextBtnNormal());
		setDrawableForView(mBtnPrevious, mSkin.getPrevBtnNormal());
		setDrawableForView(mBtnShuffle, mSkin.getShuffleBtnOff());
		setDrawableForView(mBtnRepeat, mSkin.getRepeatBtnOff());
		setDrawableForView(mBtnPlay, mSkin.getPlayBtnNormal());
		mSlimProgress.updateSkin();
		updateUIForEq();
		if (mPlayerService == null)
			return;
		if (mPlayerService.isPlaying()) {
			setDrawableForView(mBtnPlay, mSkin.getPauseBtnNormal());
		} else {
			setDrawableForView(mBtnPlay, mSkin.getPlayBtnNormal());
		}
	}

	private TextView setupTextForSwitcher(int color, float size) {
		TextView tv = new TextView(getApplicationContext());
		tv.setTextColor(color);
		tv.setTextSize(size);
		tv.setSingleLine(true);
		tv.setEllipsize(TruncateAt.MARQUEE);
		return tv;
	}

	private void setupAnimationForTextSwitcher(TextSwitcher ts, int inId,
			int outId) {
		ts.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
				inId));
		ts.setOutAnimation(AnimationUtils.loadAnimation(
				getApplicationContext(), outId));
	}

	private void initVars() {
		mFragmentList = new ArrayList<Fragment>();
		mPlaylist = new Playlist(getApplicationContext());
		mToast = new ToastMessage(getApplicationContext());
		mGesture = new GestureDetectorCompat(getApplicationContext(), this);
	}

	private void initPager() {
		if (mFragmentList == null)
			mFragmentList = new ArrayList<Fragment>();
		if (mFragmentList.size() <= 0) {
			mFragmentList.add(new MainSongListFragment());
			mFragmentList.add(new MainAlbumArtFragment());
			mFragmentList.add(new MainLyricsFragment());
		}

		MainPagerAdapter pagerAdapter = new MainPagerAdapter(
				getSupportFragmentManager(), mFragmentList);
		mMainPager.setAdapter(pagerAdapter);
		mMainPager.setCurrentItem(1);// Album art
	}

	private void applyRingtone(int songId) {
		Song song = getPlaylist().getSongById(songId);
		if (song == null)
			return;
		// delete before add new ringtone
		Uri uriDel = MediaStore.Audio.Media.getContentUriForPath(mPlayerService
				.getCurrentSong().getAddress());
		getContentResolver()
				.delete(uriDel,
						MediaStore.MediaColumns.DATA + "=\""
								+ song.getAddress() + "\"", null);

		ContentValues values = new ContentValues();
		values.put(MediaStore.MediaColumns.DATA, song.getAddress());
		values.put(MediaStore.MediaColumns.TITLE, song.getTitle());
		values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mpeg"); // assuming
																		// //
																		// course
		values.put(MediaStore.Audio.Media.ARTIST, song.getArtist());
		// values.put(MediaStore.Audio.Media.DURATION,
		// duration); //
		// doesn't appear to be necessary if you don't know
		values.put(MediaStore.Audio.Media.IS_RINGTONE, true);

		Uri uri = MediaStore.Audio.Media
				.getContentUriForPath(song.getAddress());
		Uri newUri = getContentResolver().insert(uri, values);

		RingtoneManager.setActualDefaultRingtoneUri(getApplicationContext(),
				RingtoneManager.TYPE_RINGTONE, newUri);
	}

	private void showToolboxExtras() {
		if (mPlaylist.getSongList() == null
				|| mPlaylist.getSongList().size() < 1) {
			mToast.showShortMessage(getString(R.string.toast_empty_song_list));
			return;
		}
		if (mToolbox.isShowing())
			return;
		mToolbox.setContentLayout(R.layout.tool_box_player_extras);
		mToolbox.show();
		final ViewFlipper viewFlipper = (ViewFlipper) mToolbox
				.findViewById(R.id.view_flipper_toolbox_player);

		setBackgroundColorForView(viewFlipper);
		TextView btnEditTag = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_edit_tags);
		btnEditTag.setTextColor(mTheme.getNormalTextColor());
		btnEditTag.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					Intent i = new Intent(MainActivity.this,
							EditTagInfoActivity.class);
					int songId = MainActivity.this.getCurrentSongId();
					i.putExtra(MainActivity.INTENT_DATA_MAIN_EDIT_TAGS_SONG_ID,
							songId);
					startActivityForResult(i, Common.REQUEST_CODE_FOR_EDIT_TAGS);
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					// unbindDrawables(mLayoutToolBox);
					// mLayoutToolBox.setVisibility(View.GONE);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		TextView btnSearch = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_search);
		btnSearch.setTextColor(mTheme.getNormalTextColor());
		btnSearch.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					Intent i = new Intent(MainActivity.this,
							SearchActivity.class);
					// int songId = MainActivity.this.getCurrentSongId();
					// i.putExtra(MainActivity.INTENT_DATA_MAIN_EDIT_TAGS_SONG_ID,
					// songId);
					startActivityForResult(i, Common.REQUEST_CODE_FOR_EDIT_TAGS);
					// unbindDrawables(mLayoutToolBox);
					// mLayoutToolBox.setVisibility(View.GONE);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		TextView btnSetRingtone = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_set_rington);
		btnSetRingtone.setTextColor(mTheme.getNormalTextColor());
		btnSetRingtone.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					setAsRingtone(getCurrentSongId());
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					// unbindDrawables(mLayoutToolBox);
					// mLayoutToolBox.setVisibility(View.GONE);
					mToolbox.close();

					break;
				}
				return true;
			}
		});

		TextView btnSendFile = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_send_file);
		btnSendFile.setTextColor(mTheme.getNormalTextColor());
		btnSendFile.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					sendFile(getCurrentSongId());
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					// unbindDrawables(mLayoutToolBox);
					// mLayoutToolBox.setVisibility(View.GONE);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		TextView btnDetail = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_view_detail);
		btnDetail.setTextColor(mTheme.getNormalTextColor());
		btnDetail.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					goToDetail(getCurrentSongId());
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					// unbindDrawables(mLayoutToolBox);
					// mLayoutToolBox.setVisibility(View.GONE);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		final TextView tvMin = (TextView) mToolbox
				.findViewById(R.id.tv_alarm_toolbox_player_sub_1);
		tvMin.setTextColor(mTheme.getNormalTextColor());
		((TextView) mToolbox
				.findViewById(R.id.tv_static_max_alarm_toolbox_player_sub_1))
				.setTextColor(mTheme.getNormalTextColor());
		((TextView) mToolbox
				.findViewById(R.id.tv_static_min_alarm_toolbox_player_sub_1))
				.setTextColor(mTheme.getNormalTextColor());
		final SlimProgressBar slimProgress = (SlimProgressBar) mToolbox
				.findViewById(R.id.progress_alarm_toolbox_player_sub_1);
		slimProgress.setMax(90);
		slimProgress.setProgress(15);
		slimProgress.setOnSlimClicked(new SlimProgressClicked() {

			@Override
			public void onClick(int newProgress) {
				if (newProgress < 1) {
					newProgress = 1;
					slimProgress.setProgress(newProgress);
				}
				tvMin.setText(newProgress + "");
			}
		});
		TextView btnAlarmOk = (TextView) mToolbox
				.findViewById(R.id.tv_ok_alarm_toolbox_player_sub_1);
		btnAlarmOk.setTextColor(mTheme.getNormalTextColor());
		btnAlarmOk.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					if (getPlayerService().isPlaying()) {
						Intent myIntent = new Intent(MainActivity.this,
								PlayerService.class);
						myIntent.putExtra(
								PlayerService.INTENT_SERVICE_COMMAND,
								PlayerService.SERVICE_COMMAND_NOTIFICATION_CLOSE);
						PendingIntent pendingIntent = PendingIntent.getService(
								getApplicationContext(), 0, myIntent, 0);

						AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
						Calendar calendar = Calendar.getInstance();
						calendar.setTimeInMillis(System.currentTimeMillis());
						calendar.add(Calendar.MINUTE,
								slimProgress.getProgress());
						alarmManager.set(AlarmManager.RTC_WAKEUP,
								calendar.getTimeInMillis(), pendingIntent);

						getToast()
								.showLongMessage(
										getString(R.string.tool_box_alarm_toast_set_up));
					} else {
						getToast()
								.showLongMessage(
										getString(R.string.tool_box_alarm_toast_not_set_up));
					}
					// unbindDrawables(mLayoutToolBox);
					// mLayoutToolBox.setVisibility(View.GONE);
					mToolbox.close();
					mIsSubToolboxShowing = false;
					break;
				}
				return true;
			}
		});

		TextView btnAlarm = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_alarm);
		btnAlarm.setTextColor(mTheme.getNormalTextColor());
		btnAlarm.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					// Setup animation
					viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_right_to_left_fade_in_fast));
					viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_right_to_left_fade_out_fast));
					viewFlipper.setDisplayedChild(1);

					// re-setup animation
					viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_left_to_right_fade_in_fast));
					viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_left_to_right_fade_out_fast));
					mIsSubToolboxShowing = true;
					break;
				}
				return true;
			}

		});

		TextView btnMenu = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_menu);
		btnMenu.setTextColor(mTheme.getNormalTextColor());
		btnMenu.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);

					// Setup animation
					viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_right_to_left_fade_in_fast));
					viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_right_to_left_fade_out_fast));
					viewFlipper.setDisplayedChild(2);

					// re-setup animation
					viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_left_to_right_fade_in_fast));
					viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_left_to_right_fade_out_fast));
					break;
				}
				return true;
			}

		});

		setupToolbox(viewFlipper);

	}

	public void sendFile(int songId) {
		if (mPlayerService != null) {
			Song s = getPlaylist().getSongById(songId);
			if (s == null)
				return;
			String path = s.getAddress();

			File file = new File(path);

			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
			startActivity(intent);
		}
	}

	public void goToDetail(int songId) {
		if (mPlayerService != null) {
			Song s = getPlaylist().getSongById(songId);
			if (s == null)
				return;
			Intent i = new Intent(MainActivity.this, SongDetailsActivity.class);

			i.putExtra(INTENT_DATA_MAIN_VIEW_DETAILS_SONG_ID, s.getId());
			startActivity(i);
		}
	}

	public void setAsRingtone(final int songId) {
		if (mPlayerService != null) {
			OnTouchListener okEvent = new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (!mIsMessageBoxReady)
						return true;
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						setAlpha(v, 0.5f);
						return true;
					case MotionEvent.ACTION_UP:
						setAlpha(v, 1.0f);
						mIsMessageBoxReady = false;
						dismissMessageBox();
						applyRingtone(songId);
						mToast.showLongMessage(getString(R.string.main_ringtone_toast_changed_ok));
						return true;
					default:
						break;
					}
					return false;
				}
			};

			OnTouchListener cancelEvent = new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (!mIsMessageBoxReady)
						return true;
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						setAlpha(v, 0.5f);
						return true;
					case MotionEvent.ACTION_UP:
						setAlpha(v, 1.0f);
						mIsMessageBoxReady = false;
						dismissMessageBox();
						return true;

					default:
						break;
					}
					return false;
				}
			};
			if (!mIsMessageBoxReady)
				return;
			showMessageBox(getString(R.string.message_box_apply_ringtone)
					+ "\n\n" + getPlaylist().getSongById(songId).getTitle(),
					okEvent, cancelEvent);
		} else {
			mToast.showLongMessage(getString(R.string.main_ringtone_toast_changed_not_ok));
		}
	}

	private void showToolbox() {
		if (mToolbox.isShowing())
			return;
		mToolbox.setContentLayout(R.layout.tool_box_player);
		mToolbox.show();
		setBackgroundColorForView(mToolbox.getContent());
		setupToolbox(null);
	}

	private void setupToolbox(final ViewFlipper viewFlipper) {
		if (mToolbox == null)
			return;
		TextView btnLib = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_library);
		btnLib.setTextColor(mTheme.getNormalTextColor());
		btnLib.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					Intent i = new Intent(MainActivity.this,
							LibraryActivity.class);
					startActivityForResult(i, Common.REQUEST_CODE_MAIN_LIBRARY);
					// Create animation
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		TextView btnSetting = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_setting);
		btnSetting.setTextColor(mTheme.getNormalTextColor());
		btnSetting.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					Intent i = new Intent(MainActivity.this,
							SettingActivity.class);
					startActivity(i);
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		TextView btnEq = (TextView) mToolbox.findViewById(R.id.tv_tool_box_eq);
		btnEq.setTextColor(mTheme.getNormalTextColor());
		btnEq.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					if (!AudioEffectManager.isSoundEffectSupported) {
						mToast.showLongMessage(getString(R.string.toast_eq_not_support));
						break;
					}
					Intent i = new Intent(MainActivity.this,
							SoundEffectActivity.class);
					startActivity(i);
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		TextView btnVisualizer = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_visualizer);
		btnVisualizer.setTextColor(mTheme.getNormalTextColor());
		btnVisualizer.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					if (mPlaylist.getSongList() == null
							|| mPlaylist.getSongList().size() < 1) {
						mToast.showShortMessage(getString(R.string.toast_empty_song_list));
						break;
					}
					Intent i = new Intent(MainActivity.this,
							VisualizerActivity.class);
					startActivity(i);
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					// unbindDrawables(mLayoutToolBox);
					// mLayoutToolBox.setVisibility(View.GONE);
					mToolbox.close();
					break;
				}
				return true;
			}
		});

		TextView btnMenu = (TextView) mToolbox
				.findViewById(R.id.tv_tool_box_menu_back);
		if (viewFlipper == null) {
			btnMenu.setVisibility(View.INVISIBLE);
			return;
		}
		btnMenu.setVisibility(View.VISIBLE);
		btnMenu.setTextColor(mTheme.getNormalTextColor());
		btnMenu.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					break;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(v);
					viewFlipper.setDisplayedChild(0);

					// re-setup animation
					viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_left_to_right_fade_in_fast));
					viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							getApplicationContext(),
							R.anim.slide_left_to_right_fade_out_fast));
					break;
				}
				return true;
			}

		});
	}

	private boolean mIsLongClickAction;
	private Handler mLongPressHandler = new Handler();
	private Runnable mLongPressRunnable = new Runnable() {

		@Override
		public void run() {
			mIsLongClickAction = true;
			showToolbox();
		}
	};
	private int mForwardTime = 1000;
	private boolean mIsForword = true;
	private Runnable mSeekRunnable = new Runnable() {

		@Override
		public void run() {
			mIsLongClickAction = true;
			mForwardTime += 1000;
			if (mIsForword) {
				mPlayerService.playForward(mForwardTime);
			} else {
				mPlayerService.playBackward(mForwardTime);
			}
			mLongPressHandler.postDelayed(mSeekRunnable, 1000);
		}
	};
	private boolean mIsMessageBoxReady = true;
	private boolean mIsLongTouchEq;
	private boolean mIsLongTouchBass;

	public void setupListeners() {

		mLayoutMainHeaderContent.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View view, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(view, 0.5f);
					return true;
				case MotionEvent.ACTION_UP:
					setAlpha(view, 1.0f);
					Intent i = new Intent(MainActivity.this,
							LibraryActivity.class);
					startActivityForResult(i, Common.REQUEST_CODE_MAIN_LIBRARY);
					// Create animation
					overridePendingTransition(R.anim.fade_in_fast,
							R.anim.fade_out_fast);
					return true;
				}
				return false;
			}
		});

		mTvShortcut.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View view, MotionEvent mE) {
				switch (mE.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(view, 0.5f);
					return true;
				case MotionEvent.ACTION_UP:
					setAlpha(view, 1.0f);
					doLaisimAnimation(mTvShortcut);
					showToolboxExtras();
					return true;
				}
				return false;
			}
		});

		mImgViewFavorite.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View view, MotionEvent mE) {
				switch (mE.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(view, 0.5f);
					return true;
				case MotionEvent.ACTION_UP:
					setAlpha(view, 1.0f);
					doLaisimAnimation(mImgViewFavorite);
					boolean isFav = mPlayerService.isSongFavorite();
					if (isFav) {
						mPlayerService.setFavorite(false);
						// mImgViewFavorite
						// .setImageResource(R.drawable.img_btn_favorite_off);
						mImgViewFavorite.setImageDrawable(mSkin
								.getFavoriteBtnOff());
						updateFavorite(getCurrentSongId(), 0);
					} else {
						mPlayerService.setFavorite(true);
						// mImgViewFavorite
						// .setImageResource(R.drawable.img_btn_favorite_on);
						mImgViewFavorite.setImageDrawable(mSkin
								.getFavoriteBtnOn());
						updateFavorite(getCurrentSongId(), 1);
					}
					return true;
				}
				return false;
			}
		});

		mBtnNext.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent mE) {
				switch (mE.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setDrawableForView(mBtnNext, mSkin.getNextBtnPressed());
					if (mPlayerService != null && mPlayerService.isPlaying()) {
						mIsForword = true;
						mLongPressHandler.postDelayed(mSeekRunnable, 1000);
					}
					return true;
				case MotionEvent.ACTION_UP:
					doLaisimAnimation(mBtnNext);
					mLongPressHandler.removeCallbacks(mSeekRunnable);
					setDrawableForView(mBtnNext, mSkin.getNextBtnNormal());
					if (!mIsLongClickAction) {
						if (!mPlayerService.isFading()) {
							changeMainLayoutEffect();
							mPlayerService.playNext();
						}
					} else {
						mIsLongClickAction = false;
						mPlayerService.savePlayerSetting();
					}
					return true;
				}
				return false;
			}
		});

		mBtnPrevious.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent mE) {
				switch (mE.getAction()) {
				case MotionEvent.ACTION_DOWN:
					// mBtnPrevious
					setDrawableForView(mBtnPrevious, mSkin.getPrevBtnPressed());
					if (mPlayerService != null && mPlayerService.isPlaying()) {
						mIsForword = false;
						mLongPressHandler.postDelayed(mSeekRunnable, 1000);
					}
					return true;
				case MotionEvent.ACTION_UP:
					doLaisimAnimation(mBtnPrevious);
					mLongPressHandler.removeCallbacks(mSeekRunnable);
					setDrawableForView(mBtnPrevious, mSkin.getPrevBtnNormal());
					if (!mIsLongClickAction) {
						if (!mPlayerService.isFading()) {
							changeMainLayoutEffect();
							mPlayerService.playPrevious();
						}
					} else {
						mIsLongClickAction = false;
						mPlayerService.savePlayerSetting();
					}
					return true;
				}
				return false;
			}
		});

		mBtnShuffle.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					return true;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(mBtnShuffle);
					if (mPlayerService != null) {
						if (mPlayerService.IsShuffle()) {
							mPlayerService.setShuffle(false);
							setDrawableForView(mBtnShuffle,
									mSkin.getShuffleBtnOff());
							mToast.showShortMessage(getString(R.string.main_shuffle_off));
						} else {
							mPlayerService.setShuffle(true);
							setDrawableForView(mBtnShuffle,
									mSkin.getShuffleBtnOn());
							mToast.showShortMessage(getString(R.string.main_shuffle_on));
							// update repeat mode
							RepeatMode repeatMode = mPlayerService
									.getRepeatMode();
							if (repeatMode == RepeatMode.REPEAT_ONE) {
								setDrawableForView(mBtnRepeat,
										mSkin.getRepeatBtnAll());
								mPlayerService
										.setRepeatMode(RepeatMode.REPEAT_ALL);
							}
						}
						mPlayerService.savePlayerSetting();
					}
					return true;

				}
				return false;
			}
		});

		mBtnRepeat.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					return true;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(mBtnRepeat);
					if (mPlayerService != null) {
						if (mPlayerService.IsShuffle()) {
							mPlayerService.setShuffle(false);
						}
						RepeatMode repeatMode = mPlayerService.getRepeatMode();
						switch (repeatMode) {
						case NONE:
							mPlayerService.setRepeatMode(RepeatMode.REPEAT_ONE);
							setDrawableForView(mBtnRepeat,
									mSkin.getRepeatBtnOne());
							mToast.showShortMessage(getString(R.string.main_repeat_one));
							break;
						case REPEAT_ONE:
							mPlayerService.setRepeatMode(RepeatMode.REPEAT_ALL);
							setDrawableForView(mBtnRepeat,
									mSkin.getRepeatBtnAll());
							mToast.showShortMessage(getString(R.string.main_repeat_all));
							break;
						case REPEAT_ALL:
							mPlayerService.setRepeatMode(RepeatMode.NONE);
							setDrawableForView(mBtnRepeat,
									mSkin.getRepeatBtnOff());
							mToast.showShortMessage(getString(R.string.main_repeat_off));
							break;
						}
						if (!mPlayerService.IsShuffle()) {
							setDrawableForView(mBtnShuffle,
									mSkin.getShuffleBtnOff());
						}
						mPlayerService.savePlayerSetting();
					}
					return true;

				}
				return false;
			}
		});

		mBtnEq.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					return false;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(mBtnEq);
					if (!AudioEffectManager.isSoundEffectSupported) {
						mToast.showLongMessage(getString(R.string.toast_eq_not_support));
						break;
					}
					if (mIsLongTouchEq) {
						mIsLongTouchEq = false;
						return false;
					}
					if (LaisimConfig.isEqEnable) {
						AudioEffectManager.equalizer.setEnabled(false);
						setDrawableForView(mBtnEq, mSkin.getEqBtnOff());
						mToast.showShortMessage(getString(R.string.main_eq_off));
						LaisimConfig.isEqEnable = false;
					} else {
						LaisimConfig.isEqEnable = true;
						setDrawableForView(mBtnEq, mSkin.getEqBtnOn());
						if (AudioEffectManager.getCurrentAudioEffect()
								.isEqEnable()) {
							AudioEffectManager.equalizer.setEnabled(true);
							mToast.showShortMessage(getString(R.string.main_eq_on));
						} else {
							mToast.showShortMessage(getString(R.string.main_eq_on_but));
						}
					}
					return false;

				}
				return false;
			}
		});

		mBtnEq.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				if (!AudioEffectManager.isSoundEffectSupported) {
					mToast.showLongMessage(getString(R.string.toast_eq_not_support));
					return true;
				}
				mIsLongTouchEq = true;
				Intent i = new Intent(MainActivity.this,
						SoundEffectActivity.class);
				startActivity(i);
				overridePendingTransition(R.anim.fade_in_fast,
						R.anim.fade_out_fast);
				return true;
			}
		});

		mBtnBassboost.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setAlpha(v, 0.5f);
					return false;
				case MotionEvent.ACTION_UP:
					setAlpha(v, 1.0f);
					doLaisimAnimation(mBtnBassboost);
					if (!AudioEffectManager.isSoundEffectSupported) {
						mToast.showLongMessage(getString(R.string.toast_eq_not_support));
						break;
					}
					if (mIsLongTouchBass) {
						mIsLongTouchBass = false;
						return false;
					}

					if (LaisimConfig.isBassEnable) {
						AudioEffectManager.bassBoost.setEnabled(false);
						setDrawableForView(mBtnBassboost, mSkin.getBassBtnOff());
						mToast.showShortMessage(getString(R.string.main_bass_off));
						LaisimConfig.isBassEnable = false;
					} else {
						LaisimConfig.isBassEnable = true;
						setDrawableForView(mBtnBassboost, mSkin.getBassBtnOn());
						if (AudioEffectManager.getCurrentAudioEffect()
								.isBassboostEnable()) {
							AudioEffectManager.bassBoost.setEnabled(true);
							mToast.showShortMessage(getString(R.string.main_bass_on));
						} else {
							mToast.showShortMessage(getString(R.string.main_bass_on_but));
						}
					}
				}
				return false;
			}
		});

		mBtnBassboost.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				if (!AudioEffectManager.isSoundEffectSupported) {
					mToast.showLongMessage(getString(R.string.toast_eq_not_support));
					return true;
				}
				mIsLongTouchBass = true;
				Intent i = new Intent(MainActivity.this,
						SoundEffectActivity.class);
				startActivity(i);
				overridePendingTransition(R.anim.fade_in_fast,
						R.anim.fade_out_fast);
				return true;
			}
		});

		mBtnPlay.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mLongPressHandler.postDelayed(mLongPressRunnable, 1000);
					if (mPlayerService != null && !mPlayerService.isFading()) {
						if (mPlayerService.isPlaying()) {
							setDrawableForView(mBtnPlay,
									mSkin.getPauseBtnPressed());
						} else {
							setDrawableForView(mBtnPlay,
									mSkin.getPlayBtnPressed());
						}
					}
					return true;
				case MotionEvent.ACTION_UP:
					doLaisimAnimation(mBtnPlay);
					mLongPressHandler.removeCallbacks(mLongPressRunnable);
					if (mIsLongClickAction) {
						// updateNormalPausePlayEffect(false, false);
						mIsLongClickAction = false;
						updatePlayingStatus();
						return true;
					} else {
						if (mPlaylist.getCount() < 1) {
							setDrawableForView(mBtnPlay,
									mSkin.getPlayBtnNormal());
						} else {
							if (mPlayerService != null
									&& !mPlayerService.isFading()) {
								if (mPlayerService.isPlaying()) {
									mPlayerService.pause(true);
									mShouldDisplayNotification = false;
									setDrawableForView(mBtnPlay,
											mSkin.getPlayBtnNormal());
									mTvSongExtras.setSelected(false);
								} else {
									mPlayerService.start();
									mShouldDisplayNotification = true;
									setDrawableForView(mBtnPlay,
											mSkin.getPauseBtnNormal());
									mTvSongExtras.setSelected(true);
								}
							}
						}
					}

				}
				return false;
			}
		});

		mSlimProgress.setOnSlimClicked(new SlimProgressClicked() {

			@Override
			public void onClick(int newProgress) {
				mPlayerService.playTo(newProgress);
			}
		});

		mMainPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int pos) {
				if (pos == 2)// lyrics pager
				{
					mIsMainPagerLyrics = true;
					new LyricsLoader().execute();
				} else {
					mIsMainPagerLyrics = false;
					if (pos == 0) {
						if (mFragmentList.size() > 1) {
							((MainSongListFragment) mFragmentList.get(0))
									.scrollToCurrentSongIndex(mCurrentSongIndex);
						}
					}
				}

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		// mLayoutToolBox.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if (!mIsSubToolboxShowing) {
		// closeToolbox();
		// }
		// }
		// });

	}

	@Override
	protected void onActivityResult(int req, int res, Intent data) {
		super.onActivityResult(req, res, data);
		if (res == 0) {
			mNeedToUpdateUI = true;
		} else {
			mNeedToUpdateUI = false;
		}
		switch (req) {
		case Common.REQUEST_CODE_MAIN_LIBRARY:
			if (res == Common.RESULT_CODE_LIBRARY_MAIN) {
				if (mPlayerService == null) {
					// reload data...
				} else {
					mPlaylist.setSongList(mPlayerService.getSongList());
					((MainSongListFragment) mFragmentList.get(0))
							.updateAdapter();
					updateUI();
				}
			}
			break;
		case Common.REQUEST_CODE_FOR_EDIT_TAGS:
			if (res == Common.RESULT_CODE_EDIT_TAGS) {
				if (mPlayerService == null) {
					// reload data...
				} else {
					if (data == null)
						return;
					int id = data.getExtras().getInt(
							INTENT_DATA_MAIN_EDIT_TAGS_SONG_ID);
					DataBaseAccess db = DataBaseAccess
							.getInstance(getApplicationContext());
					Song s = db.getSong(id);
					if (s == null)
						return;
					Song song = getPlaylist().getSongById(id);
					song.setTitle(s.getTitle());
					song.setAlbum(s.getAlbum());
					song.setArtist(s.getArtist());
					song.setGenre(s.getGenre());
					if (song.getId() == mPlayerService.getCurrentSong().getId()) {
						mPlayerService.displayNotification(mPlayerService
								.isPlaying());
						mPlayerService.updateWidget(mPlayerService.isPlaying());
					}
					((MainSongListFragment) mFragmentList.get(0)).getAdapter()
							.setDataChanged(getPlaylist().getSongList());
					updateUI();
				}
			}
			break;
		}

	}

	public void changeMainLayoutEffect() {
		if (Utils.androidOs < Common.ANDROID_OS_GINGERBREAD_TO_ICS) {
			com.nineoldandroids.animation.ObjectAnimator oa = com.nineoldandroids.animation.ObjectAnimator
					.ofFloat(mLinearlayoutMainBg, "alpha", 1.0f, 0.0f);
			oa.setDuration(500);
			oa.start();
		} else {
			ObjectAnimator oa = ObjectAnimator.ofFloat(mLinearlayoutMainBg,
					"alpha", 1.0f, 0.0f);
			oa.setDuration(500);
			oa.start();
		}
		mShouldChangeBg = true;
	}

	private void updateUIForEq() {
		if (LaisimConfig.isEqEnable) {
			setDrawableForView(mBtnEq, (mSkin.getEqBtnOn()));
		} else {
			setDrawableForView(mBtnEq, (mSkin.getEqBtnOff()));
		}
		if (LaisimConfig.isBassEnable) {
			// mBtnBassboost
			setDrawableForView(mBtnBassboost, (mSkin.getBassBtnOn()));
		} else {
			setDrawableForView(mBtnBassboost, (mSkin.getBassBtnOff()));
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mBroadcastUpdatePlayedTime != null)
			unregisterReceiver(mBroadcastUpdatePlayedTime);
		if (mBroadcastUpdateSongInfo != null)
			unregisterReceiver(mBroadcastUpdateSongInfo);
		if (mBroadcastPauseStopSong != null)
			unregisterReceiver(mBroadcastPauseStopSong);
		// save data.
		if (mPlayerService != null)
			mPlayerService.savePlayerSetting();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.e("Onresume", "Onresume main ac called");
		if (mPlayerService != null) {
			if (mPlayerService.isPlaylistChanged()) {

				Song s = mPlayerService.getCurrentSong();
				if (s == null) {
					// some one has reset laisim
					// mPlaylist.setSongList(loadPlayingSongListFromDB());
					// mPlayerService.setPlaylist(mPlaylist.getSongList());
					((MainSongListFragment) mFragmentList.get(0))
							.updateAdapter();
					if (mPlaylist.getCount() > 0) {
						if (!mPlayerService.isPlaying())
							mPlayerService.resetAndPlay(0);
					} else {
						mPlayerService.resetLaisim(false);
					}
				} else {
					int currentSongId = s.getId();
					// mPlaylist.setSongList(loadPlayingSongListFromDB());
					// mPlayerService.setPlaylist(mPlaylist.getSongList());
					((MainSongListFragment) mFragmentList.get(0))
							.updateAdapter(currentSongId);
					if (mPlayerService.isSongChanged()) {
						mIsNeedChangedAlbumArt = true;
						if (!mPlayerService.isPlaying())
							mPlayerService.resetAndPlay(0);
					}
				}
			}
			if (mPlayerService.isSkinChanged()) {
				mIsNeedChangedAlbumArt = true;
				mPlayerService.setSkinChanged(false);
				mPlayerService.updateWidget(mPlayerService.isPlaying());
			}
			if (mPlayerService.isNeedUpdateAlbumArt()) {
				mIsNeedChangedAlbumArt = true;
				mPlayerService.setNeedUpdateAlbumArt(false);
			}
		}
		applyTheme();
		applySkin();
		registerReceiver(mBroadcastUpdatePlayedTime, new IntentFilter(
				Common.INTENT_UPDATE_TIME_PLAYED));
		registerReceiver(mBroadcastUpdateSongInfo, new IntentFilter(
				Common.INTENT_UPDATE_SONG_INFO));
		registerReceiver(mBroadcastPauseStopSong, new IntentFilter(
				Common.INTENT_STOP_SONG));
		if (!mIsBoundService) {
			Log.e("MainAc", "Onresume binding");
			doBindService();
		}

		mIsDisplayAlbumArt = isAlbumArt();
		// check if need refresh view
		if (mPlayerService == null) {
			Log.e("MainAc", "Player Service null");
			return;
		}
		// if (mNeedToUpdateUI)
		updateUI();
		// if (mCurrentSongIndex != mPlayerService.getCurrentSongIndex()) {
		// }
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mIsBoundService) {
			doUnBindService();
		}
	}

	private void updatePlayingStatus() {
		if (mSkin == null)
			return;
		if (mPlayerService.isPlaying()) {
			setDrawableForView(mBtnPlay, mSkin.getPauseBtnNormal());

		} else {
			setDrawableForView(mBtnPlay, mSkin.getPlayBtnNormal());
		}
	}

	public void updateCurrentIndex() {
		mTextSwitcherCurrentIndex.setText(mCurrentSongIndex + 1 + "");
		mTvTotalSong.setText("/" + mPlaylist.getCount());
	}

	private void updateUI() {
		// Log.e("MainAc", "Update UI get called");
		int playingIndex = mPlayerService.getCurrentSongIndex();
		if (playingIndex == -1) {
			resetLaiSimUI();
			return;
		}
		// MainAlbumArtFragment abFrag = (MainAlbumArtFragment)
		// mFragmentList
		// .get(1);// ALbum art
		if (mFragmentList.size() <= 0)
			initPager();

		Song song = mPlayerService.getCurrentSong();
		if (song == null)
			return;
		// Update fav icon
		if (song.isFavorite()) {
			// mImgViewFavorite.setImageResource(R.drawable.img_btn_favorite_on);
			mImgViewFavorite.setImageDrawable(mSkin.getFavoriteBtnOn());
		} else {
			// mImgViewFavorite.setImageResource(R.drawable.img_btn_favorite_off);
			mImgViewFavorite.setImageDrawable(mSkin.getFavoriteBtnOff());
		}

		// Update album art
		if (mCurrentSongIndex != playingIndex || mIsNeedChangedAlbumArt) {
			if (Utils.androidOs > Common.ANDROID_OS_GINGERBREAD) {
				new AlbumArtExtracter().executeOnExecutor(
						AsyncTask.THREAD_POOL_EXECUTOR, song);
			} else {
				new AlbumArtExtracter().execute(song);
			}
		} else {
			// album art not changed but the blur need to update
			if (mIsNeedToBlur) {
				mIsNeedToBlur = false;
				setBackgroundBlur(mAlbumArtBitmap, true);
			}
		}

		mCurrentSongIndex = playingIndex;
		// update the list to the current song position
		if (mMainPager.getCurrentItem() == 0) {
			if (mFragmentList.size() > 1) {
				((MainSongListFragment) mFragmentList.get(0))
						.scrollToCurrentSongIndex(mCurrentSongIndex);
			}
		}
		// update current index textview
		updateCurrentIndex();

		mTvSongTitle.setText(song.getTitle());
		mTvArtist.setText(song.getArtist());
		int tdur = mPlayerService.getCurrentSongDuration();
		// mSeekBarPlaying.setMax(tdur);
		mSlimProgress.setMax(tdur);
		String dur = Utils.convertTimeToString(tdur);
		mTvDuration.setText(dur);
		// Update Progress bar and textview

		int sdur = mPlayerService.getCurrentSongPlayedTime();
		// mSeekBarPlaying.setProgress(sdur);
		mSlimProgress.setProgress(sdur);
		// if(sdur==0){
		// sdur =
		mTvCurrentDuration.setText(Utils.convertTimeToString(sdur));

		// Update lyrics
		if (mShouldUpdateLyrics && mIsMainPagerLyrics) {
			new LyricsLoader().execute();
		}

		// update extras info
		mTvSongExtras.setText(song.getTitle() + " - " + song.getAlbum() + " - "
				+ song.getArtist() + " - " + song.getBitRateString());

		// Update selected item on Listview
		MainSongListFragment mF = ((MainSongListFragment) mFragmentList.get(0));
		mF.updateListView();

		updatePlayingStatus();

		// Update shuffle repeat button
		if (mPlayerService.IsShuffle()) {
			setDrawableForView(mBtnShuffle, mSkin.getShuffleBtnOn());
		} else {
			setDrawableForView(mBtnShuffle, mSkin.getShuffleBtnOff());
		}

		RepeatMode rM = mPlayerService.getRepeatMode();
		if (rM == RepeatMode.NONE) {
			setDrawableForView(mBtnRepeat, mSkin.getRepeatBtnOff());
		} else if (rM == RepeatMode.REPEAT_ONE) {
			setDrawableForView(mBtnRepeat, mSkin.getRepeatBtnOne());
		} else {
			setDrawableForView(mBtnRepeat, mSkin.getRepeatBtnAll());
		}
		mNeedToUpdateUI = false;
		updateSongPlayedPlay(getCurrentSongId(), song.getPlayedTime());
		updatePlayingSongIdPlaylist(getCurrentSongId());

	}

	public void setBackgroundBlur(Bitmap bm, boolean isBlur) {
		if (bm == null)
			return;
		if (bm.isRecycled())
			return;
		new BackgroundBlurer(isBlur).execute(Utils.createSmallBitmap(bm));
	}

	private void resetLaiSimUI() {
		int playingIndex = -1;
		((MainAlbumArtFragment) mFragmentList.get(1)).updateAnimation(
				R.anim.fade_in, R.anim.fade_out_fast);

		// Update fav icon
		mImgViewFavorite.setImageDrawable(mSkin.getFavoriteBtnOff());

		// // Update album art
		if (mCurrentSongIndex != playingIndex) {
			mAlbumArtBitmap = ((BitmapDrawable) mSkin.getDefaultAlbum())
					.getBitmap();
			MainAlbumArtFragment maa = ((MainAlbumArtFragment) mFragmentList
					.get(1));
			// if(maa.getImageBitmap()!=null)
			maa.setImage(getApplicationContext(), mAlbumArtBitmap);
			mLinearlayoutMainBg.setBackgroundColor(0x0106000d);
		}

		mCurrentSongIndex = playingIndex;

		updateCurrentIndex();
		mTvSongTitle.setText(getString(R.string.app_name));
		mTvArtist.setText(getString(R.string.app_name));
		int tdur = mPlayerService.getCurrentSongDuration();
		// mSeekBarPlaying.setMax(tdur);
		mSlimProgress.setMax(tdur);
		mTvDuration
				.setText(getString(R.string.common_text_max_total_time_default));
		// Update Progress bar and textview
		mSlimProgress.setProgress(0);
		mTvCurrentDuration
				.setText(getString(R.string.common_text_played_time_default));

		// update extras info
		mTvSongExtras.setText("");
		updatePlayingStatus();

		// Update shuffle repeat button
		if (mPlayerService.IsShuffle()) {
			setDrawableForView(mBtnShuffle, mSkin.getShuffleBtnOn());
		} else {
			setDrawableForView(mBtnShuffle, mSkin.getShuffleBtnOff());
		}

		RepeatMode rM = mPlayerService.getRepeatMode();
		if (rM == RepeatMode.NONE) {
			setDrawableForView(mBtnRepeat, mSkin.getRepeatBtnOff());
		} else if (rM == RepeatMode.REPEAT_ONE) {
			setDrawableForView(mBtnRepeat, mSkin.getRepeatBtnOne());
		} else {
			setDrawableForView(mBtnRepeat, mSkin.getRepeatBtnAll());
		}
		mNeedToUpdateUI = false;

	}

	// //////////////////////////////////////////////////////
	//
	// Database, Storage...
	//
	// //////////////////////////////////////////////////////

	private boolean isAlbumArt() {
		SharedPreferences sp = getSharedPreferences(
				Common.SP_ALBUM_ART_SETTING_NAME, MODE_PRIVATE);
		return sp.getBoolean(Common.SP_ALBUM_ART_IS_DISPLAY_ALBUM_ART, true);
	}

	// private void saveSongListToDB(List<Song> l) {
	// mDatabase = DataBaseAccess.getInstance(getApplicationContext());
	// for (Song s : l) {
	// mDatabase.addSong(s);
	// }
	//
	// }
	//
	// private List<Song> loadSongListFromDB() {
	// List<Song> songs = new ArrayList<Song>();
	// mDatabase = DataBaseAccess.getInstance(getApplicationContext());
	// songs = mDatabase.getAllSong();
	//
	// // reset the current playing list is all song
	// SharedPreferences sP = getSharedPreferences(Common.SP_LIBRARY_NAME,
	// Context.MODE_PRIVATE);
	// SharedPreferences.Editor ed = sP.edit();
	// ed.putInt(Common.SP_LIBRARY_PLAYING_LIB_INDEX, 2);
	// ed.commit();
	// return songs;
	// }

	// private List<Song> loadPlayingSongListFromDB() {
	// mDatabase = DataBaseAccess.getInstance(getApplicationContext());
	// List<Song> songs = mDatabase.getSavedPlayingSong();
	//
	// if (songs == null || songs.size() <= 0)
	// return loadSongListFromDB();
	// return songs;
	// }

	public String loadSongLyrics(int songId) {
		if (songId == -1)
			return getString(R.string.mpsl_lyrics_no_data);
		mDatabase = DataBaseAccess.getInstance(getApplicationContext());
		String lyrics = mDatabase.getSongLyrics(songId);

		return lyrics;

	}

	public void updateSongLyrics(int songId, String lyrics) {
		mDatabase = DataBaseAccess.getInstance(getApplicationContext());
		mDatabase.updateLyrics(songId, lyrics);

	}

	public void deleteSongLyrics(int songId) {
		mDatabase = DataBaseAccess.getInstance(getApplicationContext());
		mDatabase.deleteLyrics(songId);

	}

	public void updateFavorite(int songId, int value) {
		mDatabase = DataBaseAccess.getInstance(getApplicationContext());
		mDatabase.updateFavorite(songId, value);

	}

	public void updateSongPlayedPlay(int songId, int value) {
		mDatabase = DataBaseAccess.getInstance(getApplicationContext());
		mDatabase.updateSongPlayedTime(songId, value);

	}

	public void updatePlayingSongIdPlaylist(int songId) {
		mDatabase = DataBaseAccess.getInstance(getApplicationContext());
		int pId = mDatabase.getPlayingPlaylistId();
		if (pId > 0) {
			mDatabase.setPlayingSongIdInPlaylist(pId, songId);
		}

	}

	public boolean isAlbumArtHidden(int songId) {
		DataBaseAccess db = DataBaseAccess.getInstance(getApplicationContext());
		if (db.isAlbumArtHidden(songId) == 0) {

			return true;
		}

		return false;
	}

	public void removeSong(int index) {
		mPlaylist.removeSong(index);
	}

	// private ArrayList<String> getSongAddressList() {
	// if (mPlaylist == null || mPlaylist.getCount() <= 0)
	// return null;
	// ArrayList<String> addressList = new ArrayList<String>();
	// for (Song s : mPlaylist.getSongList()) {
	// addressList.add(s.getAddress());
	// }
	// return addressList;
	// }

	// //////////////////////////////////////////////////////
	//
	// Custom edge and glow effect
	//
	// //////////////////////////////////////////////////////
	private void setGlowEffectColor(int color) {
		int glowDrawableId = getResources().getIdentifier("overscroll_glow",
				"drawable", "android");
		Drawable androidGlow = getResources().getDrawable(glowDrawableId);
		androidGlow.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
	}

	private void setEdgeEffectColor(int color) {
		int edgeDrawableId = getResources().getIdentifier("overscroll_edge",
				"drawable", "android");
		Drawable androidEdge = getResources().getDrawable(edgeDrawableId);
		androidEdge.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
	}

	// //////////////////////////////////////////////////////
	//
	// Asynctask
	//
	// //////////////////////////////////////////////////////

	public class LyricsLoader extends AsyncTask<Void, Void, String> {
		@Override
		protected void onPreExecute() {
			// MainLyricsFragment ml = (MainLyricsFragment)
			// mFragmentList.get(2);
			// ml.setLyrics(getString(R.string.message_getting_lyrics));
		}

		@Override
		protected String doInBackground(Void... params) {
			if (mPlayerService != null) {
				return loadSongLyrics(getCurrentSongId());
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			MainLyricsFragment ml = (MainLyricsFragment) mFragmentList.get(2);
			ml.setLyrics(result);
			mShouldUpdateLyrics = false;
		}

	}

	class BackgroundBlurer extends AsyncTask<Bitmap, Void, Bitmap> {

		private boolean mIsBlur;

		public BackgroundBlurer(boolean isBlur) {
			mIsBlur = isBlur;
		}

		@Override
		protected Bitmap doInBackground(Bitmap... params) {
			// Bitmap bm = Utils.fastblur(getApplicationContext(),
			// params[0],10);
			if (mIsBlur) {
				return Utils.boxBlur(params[0], 30);
			} else {
				return params[0];
			}
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			Animator.applyAlphaAnimation(mLinearlayoutMainBg, 500, null, 0.0f,
					1.0f);
			setDrawableForView(mLinearlayoutMainBg, new BitmapDrawable(
					getApplicationContext().getResources(), result));
			mShouldChangeBg = false;
		}

	}

	class AlbumArtExtracter extends AsyncTask<Song, Void, Bitmap> {

		@Override
		protected Bitmap doInBackground(Song... params) {
			Song song = params[0];
			// user setting not to display album art
			if (mIsDisplayAlbumArt) {
				// This album art hidden by user
				if (!isAlbumArtHidden(song.getId())) {
					mIsNeedChangedAlbumArt = false;
					mAlbumArtBitmap = song
							.extractAlbumArt(getApplicationContext());
					// if(maa.getImageBitmap()!=null)
					return mAlbumArtBitmap;
				} else {
					return null;
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			MainAlbumArtFragment maa = ((MainAlbumArtFragment) mFragmentList
					.get(1));
			if (result != null) {

				maa.setImage(getApplicationContext(), mAlbumArtBitmap);
				if (mAlbumArtBitmap != null && !mAlbumArtBitmap.isRecycled()) {
					setBackgroundBlur(mAlbumArtBitmap, true);
				}
			} else {
				maa.setImage(getApplicationContext(),
						((BitmapDrawable) ThemeManager.getSelectedSkin()
								.getDefaultAlbum()).getBitmap());
				setBackgroundToDefault();
			}
		}

	}

	// //////////////////////////////////////////////////////
	//
	// Shared preference
	//
	// //////////////////////////////////////////////////////

	// //////////////////////////////////////////////////////
	//
	// Get.....
	//
	// //////////////////////////////////////////////////////

	public Playlist getPlaylist() {
		return mPlaylist == null ? new Playlist(getApplicationContext())
				: mPlaylist;
	}

	public Toolbox getToolBox() {
		return mToolbox;
	}

	public String getCurrentSongTitle() {
		if (mPlayerService == null)
			return null;
		if (mPlayerService.getCurrentSong() == null)
			return null;
		return mPlayerService.getCurrentSong().getTitle();
	}

	public int getCurrentSongId() {
		if (mPlayerService == null)
			return -1;
		Song s = mPlayerService.getCurrentSong();
		if (s == null)
			return -1;
		return s.getId();
	}

	public void setCurrentSongIndex(int index) {
		mCurrentSongIndex = index;
		mPlayerService.setCurrentSongIndex(mCurrentSongIndex);
	}

	public void requestUpdateLyrics() {
		new LyricsLoader().execute();
	}

	public ToastMessage getToast() {
		return mToast;
	}

	public void setNeedUpdateUI(boolean val) {
		this.mNeedToUpdateUI = val;
	}

	public void setNeedUpdateLyrics(boolean val) {
		this.mShouldUpdateLyrics = val;
	}

	public void setBackgroundToDefault() {
		mLinearlayoutMainBg.setBackgroundColor(0x0106000d);
	}

	public void showMessageBox(String content, OnTouchListener okEvent,
			OnTouchListener cancelEvent) {
		if (mMessageBox == null) {
			mMessageBox = new MessageBox(getApplicationContext(), true);
			LinearLayout.LayoutParams pr = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT);
			addContentView(mMessageBox, pr);
		}
		mMessageBox.setMessageContent(content);

		mMessageBox.setOkButtonOnTouchListener(okEvent);
		mMessageBox.setCancelButtonOnTouchListener(cancelEvent);

		// show

		Animation animation = AnimationUtils.loadAnimation(getBaseContext(),
				R.anim.message_box_slide_top_to_bottom_fade_in);
		animation.setStartOffset(0);
		animation.setFillAfter(true);
		mMessageBox.getContent().startAnimation(animation);
		animation = AnimationUtils.loadAnimation(getBaseContext(),
				R.anim.message_box_bg_fade_in_fast);
		animation.setFillAfter(true);
		animation.setStartOffset(0);
		mMessageBox.getBackgroundLayout().startAnimation(animation);
		mIsMessageBoxShowing = true;

	}

	public void dismissMessageBox() {
		Animation animation = AnimationUtils.loadAnimation(getBaseContext(),
				R.anim.message_box_slide_bottom_to_top_fade_out);
		animation.setStartOffset(0);
		animation.setFillAfter(true);
		mMessageBox.getContent().startAnimation(animation);
		mMessageBox.getContent().setVisibility(View.GONE);
		animation = AnimationUtils.loadAnimation(getBaseContext(),
				R.anim.message_box_bg_fade_out_fast);
		animation.setFillAfter(true);
		mMessageBox.getBackgroundLayout().startAnimation(animation);
		// mMessageBox.getBackgroundLayout().setClickable(false);

		animation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				((ViewManager) mMessageBox.getParent()).removeView(mMessageBox);
				mMessageBox = null;
				mIsMessageBoxShowing = false;
				mIsMessageBoxReady = true;
			}
		});

	}

	public boolean isCanClickMessageBox() {
		return mIsMessageBoxReady;
	}

	public void setCanClickMessageBox(boolean val) {
		mIsMessageBoxReady = val;
	}

	private boolean mIsSubToolboxShowing;

	@Override
	public void onBackPressed() {
		if (mIsMessageBoxShowing) {
			dismissMessageBox();
		} else if (mToolbox.isShowing()) {
			if (mIsSubToolboxShowing) {
				((ViewFlipper) findViewById(R.id.view_flipper_toolbox_player))
						.setDisplayedChild(0);
				mIsSubToolboxShowing = false;
			} else {
				// mLayoutToolBox.setVisibility(View.GONE);
				mToolbox.close();
			}
		} else {
			WelcomeActivity.isLoaded = false;
			if (mPlayerService != null) {
				mPlayerService.notifySkinReleased(true);

				// mPlayerService.updateWidget(mShouldDisplayNotification);
			}
			super.onBackPressed();
		}
	}

	private boolean mShouldDisplayNotification;

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.e("OnDestroy", "MainActivity, should dis"
				+ mShouldDisplayNotification);
		if (mSkin != null)
			mSkin.release(ThemeManager.MAIN_ACTIVYTY);
		unbindDrawables(findViewById(R.id.root_view_main_activity));
		System.gc();
		if (mPlayerService != null) {
			mPlayerService.notifySkinReleased(true);
			if (mShouldDisplayNotification) {
				if (mPlayerService.isPlaying()) {
					mPlayerService.displayNotification(true);
					mPlayerService.updateWidget(true);
				}
			} else {
				mPlayerService.updateWidget(false);
			}
		}
	}

	public void doLaisimAnimation(float x, float y) {
		mLaisimMainAnimation.animate(x, y);
	}

	public void doLaisimAnimation(View v) {
		if (v == null)
			return;
		int[] loc = new int[2];
		v.getLocationInWindow(loc);
		float x = loc[0] + v.getWidth() / 2;
		float y = loc[1] + v.getHeight() / 2;
		mLaisimMainAnimation.animate(x, y);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// super.onTouchEvent(event);
		return mGesture.onTouchEvent(event);
	}

	public Bitmap getCurrentAlbumArtBitmap() {
		return mAlbumArtBitmap;
	}

	// //////////////////////////////////////////////////////
	//
	// Gesture detecture
	// ///////////////////////////////////////////////////////
	@Override
	public boolean onDown(MotionEvent event) {
		// TODO Auto-generated method stub

		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean onSingleTapUp(MotionEvent event) {
		return false;
	}

	// //////////////////////////////////////////////////////
	//
	// End Gesture detecture
	// ///////////////////////////////////////////////////////
}
